<template>
	<div class="app_login" :style="{ backgroundImage: `url(${settings.login_bg_src}` }">
		<el-row justify="center" align="middle" class="login_main">
			<el-col :span="24">
				<div class="login_main_card">
					<el-row>
						<el-col :xs="0" :sm="0" :md="0" :lg="12" :xl="12" class="login_main_col_left">
							<div class="login_main_col_left_container">
								<transition name="el-fade-in-linear">
									<h1 v-if="show">{{ settings.login_name }}</h1>
								</transition>
							</div>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="login_main_col_right">
							<div class="login_main_col_right_container">
								<div class="login_main_col_right_container_logo">
									<el-avatar
										src="/public/logo.png"
										:style="{
											borderRadius: '4px',
											width: '200px',
											height: '90px'
										}"
										shape="square"
									></el-avatar>
								</div>
								<el-row justify="center" style="margin-bottom: 20px">
									<el-radio-group v-model="loginType">
										<el-radio-button label="username">账户登录</el-radio-button>
										<el-radio-button label="email">邮箱登录</el-radio-button>
									</el-radio-group>
								</el-row>
								<div class="login_main_col_right_container_form">
									<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="70px" :size="formSize">
										<el-form-item v-if="loginType === 'username'" label="账&nbsp;&nbsp;&nbsp;&nbsp;号" prop="username">
											<el-input v-model="ruleForm.username" prefix-icon="User" />
										</el-form-item>
										<el-form-item v-if="loginType === 'username'" label="密&nbsp;&nbsp;&nbsp;&nbsp;码" prop="password">
											<el-input v-model="ruleForm.password" prefix-icon="Lock" type="password" show-password />
										</el-form-item>
										<el-form-item v-if="loginType === 'email'" label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱" prop="email">
											<el-input v-model="ruleForm.email" prefix-icon="Message" />
										</el-form-item>

										<!-- 邮箱验证码部分保持原样 -->
										<el-form-item v-if="loginType === 'email'" label="验证码" prop="code">
											<el-row :gutter="10" align="middle">
												<el-col :span="16">
													<el-input v-model="ruleForm.code" prefix-icon="Crop" />
												</el-col>
												<el-col :span="8">
													<el-button
														type="primary"
														style="height: 32px; line-height: normal; white-space: nowrap"
														:disabled="!ruleForm.email || countdown > 0"
														@click="handleGetEmailCode"
													>
														{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
													</el-button>
												</el-col>
											</el-row>
										</el-form-item>

										<div style="display: flex; justify-content: center">
											<el-button type="primary" @click="handlePreLogin"> 立即登录 </el-button>
											<el-button @click="resetForm(ruleFormRef)"> 重置 </el-button>
										</div>
										<div style="display: flex; justify-content: center; margin-top: 10px">
											<el-button text @click="$route.push(`/register`)"> 立即注册 </el-button>
											<el-button type="danger" text @click="$route.push(`/forget`)"> 忘记密码？ </el-button>
										</div>
									</el-form>
								</div>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-col>
		</el-row>

		<!-- 验证码弹窗 -->
		<el-dialog v-model="captchaDialogVisible" title="验证码" width="380px" class="captcha-dialog">
			<el-form>
				<el-form-item>
					<div class="captcha-container">
						<div class="input-section">
							<el-input v-model="ruleForm.code" placeholder="请输入验证码" size="large" style="width: 100%" @keyup.enter="submitForm(ruleFormRef)">
								<template #prefix>
									<el-icon class="el-input__icon"><Crop /></el-icon>
								</template>
							</el-input>
						</div>
						<div class="image-section">
							<img :src="captchaImg" class="captcha-image" alt="验证码" @click="getCaptcha" />
						</div>
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: center">
					<el-button type="info" class="action-btn" @click="captchaDialogVisible = false"> 取消 </el-button>
					<el-button type="primary" class="action-btn" @click="submitForm(ruleFormRef)"> 确 认 </el-button>
				</div>
			</template>
		</el-dialog>

		<footer class="footer">
			{{ settings.copyright }}
		</footer>
	</div>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElNotification } from 'element-plus'
import useSystemStore from '@/stores/system'
import router from '@/router'
import Register from '@/views/common/login/register.vue'
import Forget from '@/views/common/login/forgetpassword.vue'
import settings from '../../../utils/settings'
import { Crop, Refresh } from '@element-plus/icons-vue'

const activeName = ref('first')
const $route = router
const systemStore = useSystemStore()
const formSize = ref('default')
const ruleFormRef = ref()
const captchaImg = ref()
const show = ref(false)
const countdown = ref(0)
const loginType = ref('username')
const captchaDialogVisible = ref(false)

const ruleForm = reactive({
	username: '',
	password: '',
	email: '',
	code: '',
	token: ''
})

// 校验规则
const rules = computed(() => {
	const isEmailLogin = loginType.value === 'email'
	return {
		username: isEmailLogin ? [] : [{ min: 5, max: 10, message: '账户名在5到10位', trigger: 'blur' }],
		password: isEmailLogin ? [] : [{ min: 5, max: 10, message: '密码在5到10位', trigger: 'blur' }],
		email: isEmailLogin ? [{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }] : [],
		code: [{ min: 5, max: 5, message: '验证码为5位', trigger: 'blur' }]
	}
})

const handlePreLogin = async () => {
	if (loginType.value === 'email') {
		return submitForm(ruleFormRef)
	}

	// 验证基础字段
	try {
		await ruleFormRef.value.validateField(['username', 'password'])
		// 获取验证码并显示弹窗
		await getCaptcha()
		captchaDialogVisible.value = true
	} catch (error) {
		ElMessage.error('请填写完整的账户名和密码')
	}
}

//登录方法
const submitForm = async formEl => {
	if (!formEl) {
		return
	}

	if (loginType.value === 'username' && !ruleForm.code) {
		ElMessage.error('请输入验证码')
		return
	}

	const params =
		loginType.value === 'email'
			? { email: ruleForm.email, code: ruleForm.code }
			: {
					username: ruleForm.username,
					password: ruleForm.password,
					code: ruleForm.code,
					token: ruleForm.token
				}

	try {
		const res = await request.post('/auth/login', params)
		systemStore.setToken(res.data.tokenInfo.tokenValue)
		ElNotification({
			title: '登录成功',
			message: `${loginType.value === 'email' ? ruleForm.email : ruleForm.username} 欢迎您!`,
			type: 'success'
		})
		captchaDialogVisible.value = false
		router.replace(res.data.roleList.includes('user') ? '/front' : '/')
	} catch (error) {
		if (loginType.value === 'username') {
			getCaptcha()
		}
	}
}

const handleGetEmailCode = async () => {
	if (!ruleForm.email) {
		ElMessage.error('请输入邮箱地址')
		return
	}

	if (countdown.value === 0) {
		countdown.value = 60
		const timer = setInterval(() => {
			countdown.value > 0 ? countdown.value-- : clearInterval(timer)
		}, 1000)
	}

	try {
		await request.get(`/auth/email/login/${ruleForm.email}`)
		ElMessage.success('验证码已发送，请查看邮箱')
	} catch (error) {
		ElMessage.error(error.response?.data?.message || '发送失败')
	}
}

//重置方法
const resetForm = formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()
	if (loginType.value === 'username') {
		getCaptcha()
	}
}

//获取验证码
const getCaptcha = async () => {
	const res = await request.get('/auth/captcha')
	captchaImg.value = res.data.captchaImg
	ruleForm.token = res.data.token
	ruleForm.code = ''
}

getCaptcha()
setTimeout(() => (show.value = true), 500)

watch(loginType, newType => {
	if (newType === 'username') {
		ruleForm.email = ''
	} else {
		ruleForm.username = ''
		ruleForm.password = ''
	}
	ruleForm.code = ''
	ruleForm.token = ''

	if (ruleFormRef.value) {
		ruleFormRef.value.clearValidate()
	}

	if (newType === 'username') {
		getCaptcha()
	}
})
</script>

<style scoped lang="scss">
.app_login {
	width: 100vw;
	height: 100vh;
	background-repeat: no-repeat;
	background-size: cover;

	/* 页脚样式，带透明灰色背景 */
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: rgba(128, 128, 128, 0.5); /* 半透明灰色背景 */
		text-align: center;
		padding: 1rem;
		color: #ffffff;
		font-size: 0.9rem;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
	}

	.login_main {
		height: 100vh;
		max-width: 50vw;
		min-width: 375px;
		margin: 0 auto;
		.login_main_card {
			background-color: #ffffff;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
			border: none;
			border-radius: 5px;
			overflow: hidden;
		}

		.login_main_col_left {
			background-image: url('/public/ikon.jpg');
			background-repeat: no-repeat;
			background-size: cover;

			.login_main_col_left_container {
				height: 60vh;
				width: 100%;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				h1 {
					font-size: 40px;
					font-family: 思源黑体;
					text-align: center;
					color: white;
				}
			}
		}

		.login_main_col_right {
			.login_main_col_right_container {
				height: 60vh;
				width: 100%;

				display: flex;
				flex-direction: column;
				justify-content: center;
				.login_main_col_right_container_logo {
					margin: 0 auto 20px;
					width: 200px;

					:deep(.el-avatar) {
						img {
							object-fit: contain; // 防止图片变形
						}
					}
				}
				h2 {
					text-align: center;
				}
				.login_main_col_right_container_form {
					width: 100%;
					padding: 0 30px;
				}
			}
		}
	}
}

:deep(.el-dialog__body img) {
	width: 100%;
	height: 40px;
}

.captcha-dialog {
	:deep(.el-dialog__header) {
		margin: 0;
		padding: 16px 20px;
		background: linear-gradient(120deg, #f8f9fc, #e9ecef);
		border-bottom: 1px solid #eee;

		.el-dialog__title {
			font-size: 18px;
			color: #2c3e50;
			font-weight: 600;
		}
	}

	.captcha-container {
		display: flex;
		align-items: center;
		gap: 12px;
		padding: 20px;

		.input-section {
			flex: 1;

			:deep(.el-input__wrapper) {
				border-radius: 6px;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

				&.is-focus {
					box-shadow: 0 0 0 1px var(--el-color-primary) inset;
				}
			}
		}

		.image-section {
			position: relative;
			flex-shrink: 0;

			.captcha-image {
				height: 40px;
				border-radius: 4px;
				border: 1px solid #ebeef5;
				cursor: pointer;
				transition: all 0.3s;

				&:hover {
					transform: translateY(-2px);
					box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
				}
			}

			.refresh-hint {
				position: absolute;
				bottom: -22px;
				right: 0;
				display: flex;
				align-items: center;
				gap: 4px;
				font-size: 12px;
				color: #909399;
				white-space: nowrap;

				.el-icon {
					animation: rotate 1.5s linear infinite;
				}
			}
		}
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		gap: 12px;
		padding: 0 20px 20px;

		.action-btn {
			padding: 10px 20px;
			border-radius: 6px;
			font-weight: 500;
			transition: all 0.3s;
		}
	}
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>
